package com.poobo.bailianlong;

import java.io.DataOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

import com.example.bailianlong.R;
import com.poobo.bailianlong.utile.CheckController;
import com.poobo.bailianlong.utile.Configure;
import com.poobo.bailianlong.utile.ConfigureRecord;
import com.poobo.bailianlong.utile.ConnectionsUtile;
import com.poobo.bailianlong.utile.DownConfigure;
import com.poobo.bailianlong.utile.HttpDownloader;
import com.poobo.bailianlong.utile.MsgHandler;

public class MainService extends Service {

	private final String ROOTCMD = "input tap 1224 687" + "\n";
	private int circleNumber = 0;
	
	private Map<Integer,Integer> map = new HashMap<Integer,Integer>();
	private boolean noTask = true;
	
	private String runningAppName = "";
	private String DEVICE_ID = "";
	
	private NetworkChangeReceiver networkChangeReceiver;
	private AppChangedReceiver appChangedReceiver;
	private LocalBroadcastManager localBroadcastManager;
//	private LocalReceiver localReceiver;
	
//	private CheckController checkController;
			
	private boolean networkState = false;
	
	private final Handler msgHandler = new MsgHandler(this);
	
	private HttpDownloader downloader = new HttpDownloader(this,msgHandler);  
	
	private Date[] specialDate;
	
	private boolean isGameTime = false; 
	private boolean hasCard = false;
	
	private String appName;
	private String packageName;
	private ConfigureRecord appRecord;
	private boolean clickedOK = false;
	
	private long lastClickTime = 0;
	private long currentClickTime = 0;
	
	private long startServiceTime = 0;
	
	private int mclickOK = 0;
	
	private int excuteTaskAgainRecordId = -2;
	
	private long lastGetPremissionTime = 0;
	
	private int permissionCount = 0;
	
	private boolean startedLiveActivity = false;
	
	private int readConfigureFailed = 0;
	
	private boolean losePermission = false;
	
	private int receiveBroadcastCount = 0;
	
	boolean gameIsRunning = false;
	
	private boolean isFirst = true;
	
	private boolean keepappThreadIsRunning = false;
	
	@Override
	public void onCreate(){
		super.onCreate();		
		upgradeRootPermission(getPackageCodePath());//获取root权限
		circleNumber = 0;
		PendingIntent pendingIntent3 = PendingIntent.getActivity(this, 0,  
                new Intent(this, MainActivity.class), 0); 
		
		Notification notification = new Notification.Builder(this).setSmallIcon(R.drawable.ic_launcher)  
				.setTicker("TickerText:" + "百炼龙正在运行")  
                .setContentTitle("百炼龙正在运行")  
                .setContentText("")  
                .setOngoing(true)
                .setContentIntent(pendingIntent3).setNumber(1).build(); 
		startForeground(1, notification);	
		
		File dirFile = new File(Environment.getExternalStorageDirectory() + "/" + "/voa");
		if(!dirFile.exists()){
			File dir = new File(Environment.getExternalStorageDirectory() + "/" + "/voa");				
			dir.mkdir();  		
		}
		
		Calendar cal2099 = Calendar.getInstance();
		cal2099.set(2099, 01, 01);
		startServiceTime = cal2099.getTimeInMillis();
		appChangedReceiver = new AppChangedReceiver();
		
		IntentFilter paintentFilter = new IntentFilter();
		paintentFilter.addAction("android.intent.action.PACKAGE_ADDED");	
		paintentFilter.addAction("android.intent.action.PACKAGE_REMOVED");
		paintentFilter.addDataScheme("package");
		registerReceiver(appChangedReceiver, paintentFilter);
		
//		localBroadcastManager = LocalBroadcastManager.getInstance(this);
//		IntentFilter bintentFilter = new IntentFilter();
//		bintentFilter = new IntentFilter();
//		bintentFilter.addAction("com.poobo.bailianlong.JOY_STICK_CHANGED_BROADCAST");
//		bintentFilter.addAction("com.poobo.bailianlong.JOY_STICK_LOSE_PERMISSION_BROADCAST");
//		bintentFilter.addAction("com.poobo.bailianlong.JOY_STICK_LOSE_PERMISSION_LATER_BROADCAST");
//		localReceiver = new LocalReceiver();
//		localBroadcastManager.registerReceiver(localReceiver, bintentFilter); 
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		//开机点击两次确定
//		Log.e("Bililong","mclickOk:" + mclickOK);
		
		
		if (keepappThreadIsRunning) {
			ActivityCollector.finishAll();
			Log.e("Bililong", "keepappThreadIsRunning");
			return super.onStartCommand(intent, flags, startId); 
		}
		
		 if(mclickOK < 3){
				 ActivityCollector.finishAll();
				 
				 Intent i = new Intent(this, AlarmReceiver.class); 
	       		 PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
	       		 AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
	       		 manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+2000,pi);  
	       		 RootShellCmd rsc = new RootShellCmd();				       							        				
//				 rsc.exec(ROOTCMD); 	
//				 // for test 、、、、、、、、、、、、、、、、、、、、、、、、、、
//				 rsc.exec(ROOTCMD); 	
				 
				 mclickOK++;
				 
				 return super.onStartCommand(intent, flags, startId);
		 }else if(mclickOK == 3){
			 
			 
			 IntentFilter nintentFilter = new IntentFilter();
			 nintentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
			 networkChangeReceiver = new NetworkChangeReceiver();
			 
			 registerReceiver(networkChangeReceiver, nintentFilter);
			 
			 initNetwork();
			 
			 if (!ConnectionsUtile.isNetwork(this)) {
					// 调用系统自带的WIFI设置界面
					setConnected();
					
//					Toast.makeText(this, "网络未连接，请连接网络",Toast.LENGTH_LONG).show();		
				}else{
					networkState = true;	
					Toast.makeText(MainService.this, "网络正常", 1000).show();
				}
				
				mclickOK++;
		 }else if(mclickOK == 9){		
//		 }else if(7<mclickOK && mclickOK <11){
			 lastGetPremissionTime = System.currentTimeMillis();
			 ActivityCollector.finishAll();
//			 if(checkController != null){
//				 
//				 checkController.stopThread();
//			 }
//			 checkController = new CheckController(MainService.this);
			 Intent i = new Intent(this, AlarmReceiver.class); 
       		 PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
       		 AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
       		 manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+2000,pi);  
       		 RootShellCmd rsc = new RootShellCmd();			
       		Toast.makeText(this, "mclickOK", 500).show();
			 rsc.exec(ROOTCMD); 	
			 mclickOK++;
			 return super.onStartCommand(intent, flags, startId);
		 }
		isGameTime = false; 
		
		Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        
        cal.set(Calendar.HOUR_OF_DAY, 2);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DAY_OF_MONTH, 0);	  
		cal.getTime().getTime();
		if(System.currentTimeMillis() < cal.getTime().getTime()+2000 
				&& System.currentTimeMillis() > cal.getTime().getTime()-1000){
			init();		
		}
		if(networkState){	
			startTask();
		}
		//由于系统刚启动时时间未校准，当时间校准后再为服务开始时间赋当前时间值
		Calendar cal2015 = Calendar.getInstance();
		cal2015.set(2015, 01, 01);
		Calendar cal2098 = Calendar.getInstance();
		cal2098.set(2098, 01, 01);
		if(startServiceTime > cal2098.getTimeInMillis() && System.currentTimeMillis() > cal2015.getTimeInMillis()){
//		if(startServiceTime > cal2098.getTimeInMillis()){ 
			startServiceTime = System.currentTimeMillis();
		}
//		startServiceTime = 0;
		if(intent == null){ 
		}
		return super.onStartCommand(intent, flags, startId);
	}
	
	/**
	 * 开始任务，若当前时间有任务，则执行，否则执行循环任务，直到最近任务开始时间
	 * @param 
	 * @return 		  		
	 */
	private void startTask(){
		Configure config = new Configure();		  
		int result = config.readConfigure(0);	
		if(result == -1){
			readConfigureFailed++;
			if(readConfigureFailed > 3){
				Log.e("Bililong","readConfigureFailed");
				init();	
			}

		}else{
			readConfigureFailed = 0;
		}
		//取消live定时
		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
		Intent iLive = new Intent(this, AlarmReceiver.class); 
		PendingIntent piLive = PendingIntent.getBroadcast(this, 1, iLive, 0);
		manager.cancel(piLive);
		long currentTime = System.currentTimeMillis();
		noTask = true;
		long alarmTime = 0;
		for (ConfigureRecord cRecord : config.configureList) {
			//判断当前时间是否有任�?
			if (System.currentTimeMillis() >= cRecord.startTime.getTime() && currentTime <= cRecord.stopTime.getTime()) { 			
				Log.d("Bililong","excute timing task");
   				noTask = false;
   				Intent i = new Intent(this, AlarmReceiver.class); 
        		PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);
        		manager.cancel(pi);
  				alarmTime = cRecord.stopTime.getTime();
  				//取消图片的alarm
				long stopAlarmTime = config.nearestTaskTime();	
				Intent i1 = new Intent(this, AlarmReceiver.class); 
				PendingIntent pi1 = PendingIntent.getBroadcast(this, 5, i1, 0);
				manager.set(AlarmManager.RTC_WAKEUP,stopAlarmTime,pi1);  
				Log.d("Bililong","alarm 7 " + new Date(stopAlarmTime));
  			  
  				refreshNotification("time to show" + cRecord.fileName,cRecord.fileName,"Stop time:" + cRecord.stopTime);
  				int result1 = executeTask(cRecord);
  				if(result1 == -1){ 
  				//当前任务资源尚未下载，每隔两秒重新执行一次任�?
  					final ConfigureRecord cRecordTemp = cRecord;
  					noTask = true;
  					if(excuteTaskAgainRecordId != cRecordTemp.resourceId){
  						excuteTaskAgainRecordId = cRecordTemp.resourceId;
  						new Thread() {
  	  			            public void run() {
  	  			                try {		  
  	  			                	Log.d("Bililong","再次执行任务");
  	  	 			                int result = -1;
  	  			                	while(result == -1){
  	  	  			                	Thread.sleep(20000);
  	  	  			                	if(System.currentTimeMillis() >= cRecordTemp.startTime.getTime()
  	  	  	  			              			&& System.currentTimeMillis() <= cRecordTemp.stopTime.getTime()){
  	  	  	  			              	result = executeTask(cRecordTemp);
  	  	  	  			          Log.d("Bililong","再次执行任务");
  	  	  	  			              	} 
  	  	  			                }
  	  			                } catch (InterruptedException e) {
  	  			                    e.printStackTrace();
  	  			                }  			                 			                  			              				              	     		  	
  	  			            }			        
  	  			        }.start();
  					}
  				}
  				break; 				
  			}			 
		}
		
		if(noTask){	
			refreshNotification("no tasks","no tasks","Next task start time:" +  new Date(config.nearestTaskTime()));
			alarmTime = config.nearestTaskTime();	
			if(config.configureList.size() != 0){
				executeCircle(config);	
			}else{
				Log.d("Bililong","configurelist is null");
				Message msg = qmsgHandler.obtainMessage();  
      			Bundle b = new Bundle();
                b.putString("String", "无今日配置"); 
                msg.setData(b); 			              			 
      			qmsgHandler.sendMessage(msg);  
				alarmTime = System.currentTimeMillis()+10000;
			}
		}
		Intent i = new Intent(this, AlarmReceiver.class); 
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
		manager.set(AlarmManager.RTC_WAKEUP,alarmTime,pi);  
		Log.v("Bililong","alarm 1 " + new Date(alarmTime));
	}
	/**
	 * 初始化，包括下载配置文件，删除无用文件，更新文件	
	 * @param 
	 * @return 		  		
	 */
	  private void init(){
		  Message msg = qmsgHandler.obtainMessage();  
		  Bundle b = new Bundle();
          b.putString("String", "更新配置文件"); 
          msg.setData(b); 			              			 
		  qmsgHandler.sendMessage(msg); 
		  Log.v("Bililong","init() excuted");	
		  new Thread() {
	            public void run() {
	                try {		                	
	                	DownConfigure downConfigure = new DownConfigure(DEVICE_ID);
	                    int result1 = -1;
		              	while(result1 == -1 || result1 == -2){
		              		Log.d("Bililong","下载configure");
		              		result1 = downConfigure.startDownload();	
		              		Thread.sleep(5000);
		              		if(result1 == -1){
		              			Message msg = qmsgHandler.obtainMessage();  
		              			Bundle b = new Bundle();
		                        b.putString("String", "下载配置文件失败，重新下载..."); 
		                        msg.setData(b); 			              			 
		              			qmsgHandler.sendMessage(msg);  
		              		}else if(result1 == 0){
		              			Log.d("Bililong","download successed");	
		              			Message msg = qmsgHandler.obtainMessage();  
		              			Bundle b = new Bundle();
		                        b.putString("String", "配置下载成功"); 
		                        msg.setData(b); 			              			 
		              			qmsgHandler.sendMessage(msg);  
		              			Configure config = new Configure();		  
		              			int result = config.readConfigure(0);	
		              			AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
			      				if(config.specialDate != null){
			      					specialDate = new Date[config.specialDate.length];
			      					for(int i = 0; i < config.specialDate.length; i++){	
			      						//若游戏特定任务在未来24小时内，设定定时�?
			      						if((System.currentTimeMillis() - 24*60*60*1000) < config.specialDate[i].getTime()){
			      							specialDate[i] = config.specialDate[i];
			      							Intent speciali = new Intent(MainService.this, AlarmReceiver.class); 
			      							PendingIntent specialpi = PendingIntent.getBroadcast(MainService.this, 4, speciali, 0);
			      							manager.set(AlarmManager.RTC_WAKEUP,config.specialDate[i].getTime(),specialpi); 
			      							Log.d("Bililong","specialdate:" + config.specialDate[i]);
			      						}
			      					}		
			      				}else{
			      					Log.v("Bililong","no special date");
			      				}
			      				
			      				downloader.deleteFile();	
			      				downloader.updateFile();
			      				Thread.sleep(10000);	
		              		}else if(result1 == -2){
		              			Thread.sleep(20000);	
		              			Message msg = qmsgHandler.obtainMessage();  
		              			Bundle b = new Bundle();
		                        b.putString("String", "设备未启用"); 
		                        msg.setData(b); 			              			 
		              			qmsgHandler.sendMessage(msg);  
		              			Log.d("Bililong","该设备尚未启用");	
//		              			downloader.useOldConfig();	
		              			break;
		              		}else{
		              			Message msg = qmsgHandler.obtainMessage();  
		              			Bundle b = new Bundle();
		                        b.putString("String", "连接超时或其它错误"); 
		                        msg.setData(b); 			              			 
		              			qmsgHandler.sendMessage(msg);  
		              			Log.e("Bililong","connect server timeout or other misdick");
		              			Thread.sleep(20000);	
		              			downloader.useOldConfig();		
		              		}
		              	} 
		              	
		              	
		              	
	                } catch (InterruptedException e) {
	                    e.printStackTrace();		                    
	                }		                		  	
	            }			        
	        }.start();	
	        Intent i = new Intent(MainService.this, AlarmReceiver.class); 
			PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
			AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
			//5秒钟后开始执行新配置，设置5秒时间使程序至少下载完一个图片?
			manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+5000,pi);  
			Log.v("Bililong","alarm 2 " + new Date(System.currentTimeMillis()+5000));
	  }
	  
	  /**
		 * 执行任务
		 * 判断要执行的任务资源是否下载完成
		 * 下载完成则按照图片视频或app的规则执行任务
		 * @param ConfigureRecord cRecord
		 * @return
		 */
	  private int executeTask(ConfigureRecord cRecord){
		  Log.v("Bililong","__________________________");
		  if(downloader.getMap() == null){
			  return -1;
		  }
		  map = downloader.getMap();
		  if(map.get(cRecord.resourceId) == null){
			  if(cRecord.resourceType == 1){
				  Intent i = new Intent(this, AlarmReceiver.class); 
				  PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
				  AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
				  manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+1000,pi);  
				  Log.v("Bililong","alarm 3 " + new Date(System.currentTimeMillis()+1000));
			  }else if (cRecord.resourceType == 0) {//主要修改此处0315
				  Intent i = new Intent(this, AlarmReceiver.class); 
				  PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
				  AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
				  manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+4000,pi);      
			}
			  Log.d("Bililong","当前资源尚未下载");			  
			  return -1;
		  }
		  Log.v("Bililong",cRecord.resourceId+" showtime: " + cRecord.showTime);
		  Log.e("Bililong","map:"+map);
			boolean notStartThread = false;
		  if(map.get(cRecord.resourceId).intValue() == -1){
			  
			  return -1;
		  }
		  
		  if(cRecord.resourceType == 0){			  
			  //apk
			  if(map.get(cRecord.resourceId).intValue() == -1){
				  
				  Configure config = new Configure();	
				  config.readConfigure(0);
				  executeCircle(config);
				  
				  notStartThread = true;
				  return -1;
			  }
			  if(map.get(cRecord.resourceId).intValue() == 4){
				  
				  Configure config = new Configure();	
				  config.readConfigure(0);
				  executeCircle(config);
				  
				  notStartThread = true;
				  return -1;
			  }else if(map.get(cRecord.resourceId).intValue() == 2){
				  
				  Configure config = new Configure();	
				  config.readConfigure(0);
				  executeCircle(config);
				  
				  notStartThread = true;
				  return -1;
			  }else if(map.get(cRecord.resourceId).intValue() == 5){
				  
				  Configure config = new Configure();	
				  config.readConfigure(0);
				  executeCircle(config);
				  
				  notStartThread = true;
				  return -1;
			  }
			  
			  isGameTime = true;
			  if(map.get(cRecord.resourceId).intValue() == 0 || map.get(cRecord.resourceId).intValue() == 2){
				  Log.e("Bililong","游戏未安装");
				  notStartThread = true;
			  }else if(cRecord.version.equals("null")){
				  Log.e("Bililong","未指定游戏");
				  notStartThread = true;
			  }else{
//				  Log.e("Bililong", "notStartThread:" + notStartThread);
//				  if((System.currentTimeMillis() - startServiceTime) > 10000 && !notStartThread){//此处时间参数可能仍需修改
//					  Log.v("Bililong","启动插卡线程33333333");
//					  appName = cRecord.appName;
//					  packageName =downloader.queryAppInfo(cRecord.appName,2);
//					  appRecord = cRecord;
//				  }else if (!notStartThread){
//					  Intent i = new Intent(this, AlarmReceiver.class); 
//					  PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
//					  AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
//					  Log.e("Bililong", "2222222222set alarm click:" + new Date(startServiceTime+11000) + "now:" + new Date(System.currentTimeMillis()));
//					  manager.set(AlarmManager.RTC_WAKEUP,startServiceTime+41000,pi);      
//				  }
				  Log.v("Bililong","it is gametime");
				  clickOk();
				  
//				  Configure config = new Configure();	
//				  config.readConfigure(0);
				  
//				  if(checkController != null){
//					  
//						 checkController.stopThread();
//				  }
//				  checkController = new CheckController(MainService.this);
//				  checkController = CheckController.getInstance(MainService.this);
//				  checkController.startThread();
//				  
//				  executeCircle(config);
				  
//				  clickOk();//for test
			  }			  			  
		  }	
		  
		  if(cRecord.resourceType == 2){
			  //picture			   	 
			  Log.e("Bililong", cRecord.fileName);
    		  Intent intent = new Intent(this, ShowImage.class); 	
			  intent.putExtra("fileName", cRecord.fileName); 
		      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);		      
		      startActivity(intent);  
		  }
		  if(cRecord.resourceType == 1){
			  //video 
//			  Intent intent = new Intent(this, VideosPlayActivity.class); 			   
//			  Message msg = qmsgHandler.obtainMessage();  
//			  Bundle b = new Bundle();
//	          b.putString("String", "map:"+map); 
//	          msg.setData(b); 			              			 
//			  qmsgHandler.sendMessage(msg);  
				
			  Intent intent = new Intent(this, VideoViewActivity.class); 			   
			  intent.putExtra("fileName", cRecord.fileName); 
		      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		      startActivity(intent);  			  	 
		  }
		  if(cRecord.resourceType == 4){
			  //live
			  if(startedLiveActivity == false){
				  Intent intent = new Intent(this, LiveActivity.class); 			   
				  intent.putExtra("url", cRecord.URL); 
			      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			      startActivity(intent);
			      startedLiveActivity = true;
			  }else{
				  //由于定时器不准，每隔30秒设定一次
				  Log.v("Bililong","live check");
				  Intent i = new Intent(this, AlarmReceiver.class); 
				  PendingIntent pi = PendingIntent.getBroadcast(this, 3, i, 0);    		
				  AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
				  manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+30000,pi);   
			  }
			 
		  }
		  return 0;
	  }

	  /**
		 * 无任务时执行循环任务，以任务开始时间排序，依次执行图片和视频任务，apk任务不执行。
		 * @param Configure config
		 * @return 		 		
		 */
	  private void executeCircle(Configure config){

		    long circleAlarmTime = 0; 
	        Comparator<ConfigureRecord> comparator = new Comparator<ConfigureRecord>(){ 
	      	  public int compare(ConfigureRecord r1, ConfigureRecord r2) {
	      		 if(r1.orderNumber < r2.orderNumber){
	      		 	return -1;
	      		 }else if (r1.orderNumber > r2.orderNumber){
	      			return 1;
	      		 }
	      		 return 0;	      		  
	      	  }
	        };
	        Collections.sort(config.configureList, comparator);	        
	        ArrayList<ConfigureRecord> circleList = new ArrayList<ConfigureRecord>();
	        circleList.add(config.configureList.get(0));
	        for(int i = 1; i < config.configureList.size(); i++){
	        	if(config.configureList.get(i).resourceId != config.configureList.get(i - 1).resourceId){
	        		circleList.add(config.configureList.get(i));
	        	}
	        }	       
	        if(circleList.size() < circleNumber + 
	        		1){
	        	circleNumber = 0;
	        }
	        ConfigureRecord cRecord = circleList.get(circleNumber);
        	if(cRecord.resourceType == 2){
  			  //picture
        		if(map != null && map.size() > 0 ){
        			if( map.get(cRecord.resourceId) == null || map.get(cRecord.resourceId) == -1){
            			Intent i = new Intent(this, AlarmReceiver.class); 
                		PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
                		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
                		manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),pi);  
                		circleNumber++;
                		return;
            		}
        		}
        		
        		circleAlarmTime = System.currentTimeMillis() + cRecord.showTime * 1000;
        		executeTask(cRecord); 
        		Intent i = new Intent(this, AlarmReceiver.class); 
        		PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
        		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
        		manager.set(AlarmManager.RTC_WAKEUP,circleAlarmTime,pi);  
        		Log.v("Bililong","alarm 4 " + new Date(circleAlarmTime));
        		
        		if(circleNumber < circleList.size()-1){
        			circleNumber++;
        		}else{
        			circleNumber = 0;
        		}  		     	
  		  	}else if(cRecord.resourceType == 1) {
  		  	if(map != null && map.size() > 0 ){
    			if( map.get(cRecord.resourceId) == null || map.get(cRecord.resourceId) == -1){
        			Intent i = new Intent(this, AlarmReceiver.class); 
            		PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
            		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
            		manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),pi);  
            		circleNumber++;
            		return;
        		}
    		}
  		  	
  		  		executeTask(cRecord);   		  		 		  		
	  		  	if(circleNumber < circleList.size()-1){
	    			circleNumber++;
	    		}else{
	    			circleNumber = 0;
	    		}
  		  	}
  		  	else if(cRecord.resourceType == 0){
  		  		Log.v("Bililong","this is a apk file");
	  		  	circleAlarmTime = System.currentTimeMillis();
	    		Intent i = new Intent(this, AlarmReceiver.class); 
	    		PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
	    		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
	    		manager.set(AlarmManager.RTC_WAKEUP,circleAlarmTime,pi); 
	     		Log.v("Bililong","alarm 5 " + new Date(circleAlarmTime));
				if(circleNumber < circleList.size()-1){
	    			circleNumber++;
	    		}else{
	    			circleNumber = 0;
	    		}
  		  	}else if(cRecord.resourceType == 4){
  		  		Log.v("Bililong","this is a live");
	  		  	circleAlarmTime = System.currentTimeMillis();
	    		Intent i = new Intent(this, AlarmReceiver.class); 
	    		PendingIntent pi = PendingIntent.getBroadcast(this, 1, i, 0);    		
	    		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
	    		manager.set(AlarmManager.RTC_WAKEUP,circleAlarmTime,pi);  
				if(circleNumber < circleList.size()-1){
	    			circleNumber++;
	    		}else{
	    			circleNumber = 0;
	    		}
  		  	}
	  }
	  
	  //使用adb命令杀死app 
	  private void killApp(){		 
		  		  Log.e("Bililong", "kill()");
		  PackageManager pm = this.getPackageManager(); 		
		  final String packageName ;
		  String appName = "";
		  String packageName1 = "";
			
		  Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		  mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		  List<PackageInfo> paklist = pm.getInstalledPackages(0); 
		  
		  for (int i = 0; i < paklist.size(); i++) {  
		      PackageInfo pak = (PackageInfo) paklist.get(i);	  
		      appName = pm.getApplicationLabel(pak.applicationInfo).toString();	
		      if ((appName).equals(runningAppName)) { 
		    	  packageName1 = pak.packageName;	
		    	  Log.d("Bililong","packageName:"+packageName1);
		    	  break;
	   		  }
		  }
		  packageName = packageName1;
		  
		  RootShellCmd rsc = new RootShellCmd();				       							        				
  		  rsc.exec("am force-stop " + packageName + " \n"); 
	  }
	  //当游戏开始运行后执行，监控游戏运行状态，进程关闭后启动循环任务
	  private void keepApp(final String packageName,final ConfigureRecord cRecord,final StartGame startgame){
		  
		  AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
			Intent i = new Intent(this, AlarmReceiver.class); 
			PendingIntent pi1 = PendingIntent.getBroadcast(this, 1, i, 0);
	  		manager.cancel(pi1);
	  		PendingIntent pi0 = PendingIntent.getBroadcast(this, 0, i, 0);
	  		manager.cancel(pi0);
	  		PendingIntent pi2 = PendingIntent.getBroadcast(this, 2, i, 0);
	  		manager.cancel(pi2);
	  		PendingIntent pi3 = PendingIntent.getBroadcast(this, 3, i, 0);
	  		manager.cancel(pi3);
	  		PendingIntent pi4 = PendingIntent.getBroadcast(this, 5, i, 0);
	  		manager.cancel(pi4);
	  		
		  if (keepappThreadIsRunning) {
			return;
		}else {
			
		}
		  new Thread() {
	            public void run() {
          		try {
          			
          			boolean a = System.currentTimeMillis() >= cRecord.startTime.getTime() 
          				  && System.currentTimeMillis() <= cRecord.stopTime.getTime();
//          		  if(System.currentTimeMillis() >= cRecord.startTime.getTime() 
//        				  && System.currentTimeMillis() <= cRecord.stopTime.getTime()){
        			  Log.d("Bililong","stopTime:" + cRecord.stopTime);
        			  boolean isRunning = true;
        			  while(isRunning){
        				  keepappThreadIsRunning = true;
        				  Thread.sleep(3000);
        				  isRunning = false;
        				  ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);  
          		        List<ActivityManager.RunningAppProcessInfo> appProcessList = mActivityManager  
          		                .getRunningAppProcesses();  
          		        Log.v("Bililong","keepapp");
          		        for (ActivityManager.RunningAppProcessInfo appProcess : appProcessList) {
          		        	String processName = appProcess.processName;
          		        	if(packageName.equals(processName)){        		        		
          		        		isRunning = true;
          		        		break;
          		        	}
          		        }
        			  }
//        		  }			  			  		  		  	 
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }	
          		keepappThreadIsRunning = false;
          		Intent intent2 = new Intent(MainService.this, MainActivity.class); 	
			    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);		      
			    startActivity(intent2);  
            	Log.e("Bililong","process " + cRecord.appName + " stopped.");
            	Intent i = new Intent(MainService.this, AlarmReceiver.class); 
        		PendingIntent pi = PendingIntent.getBroadcast(MainService.this, 0, i, 0);
        		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
        		manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),pi);  
        		
        		  Log.d("Bililong","cRecordNow.stopTime:" + cRecord.stopTime);
        		  gameIsRunning = false;
            }			                			                	                
		  }.start();
	  }
	  
	  //第一次运行点击确定后杀死游戏，重新启动，否则直接启动游戏
	  private void clickOk(){
		  
		 Log.e("Bililong", "click(");
		 	AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
			Intent i = new Intent(this, AlarmReceiver.class); 
			PendingIntent pi1 = PendingIntent.getBroadcast(this, 1, i, 0);
	  		manager.cancel(pi1);
	  		PendingIntent pi0 = PendingIntent.getBroadcast(this, 0, i, 0);
	  		manager.cancel(pi0);
	  		PendingIntent pi2 = PendingIntent.getBroadcast(this, 2, i, 0);
	  		manager.cancel(pi2);
	  		PendingIntent pi3 = PendingIntent.getBroadcast(this, 3, i, 0);
	  		manager.cancel(pi3);
	  		PendingIntent pi4 = PendingIntent.getBroadcast(this, 5, i, 0);
	  		manager.cancel(pi4);
	  		
		  Configure config = new Configure();		
		  config.readConfigure(0);
		  for (ConfigureRecord cRecord : config.configureList) {
			  if (System.currentTimeMillis() >= cRecord.startTime.getTime() && System.currentTimeMillis() <= cRecord.stopTime.getTime()) { 			
				  Log.d("Bililong","excute timing task startgame");
				  appName = cRecord.appName;
				  packageName =downloader.queryAppInfo(cRecord.appName,2);
				  appRecord = cRecord;	
				  break;
			  }
		  }	
		  if(appName == "Bililong"){
			  return;
		  }
		  final StartGame startgame = new StartGame(this);
		  
		  //启动游戏
		  startgame.startGameByName(appName);
		  runningAppName = appName;
		  gameIsRunning = true;
		  final String packageName =downloader.queryAppInfo(appName,2);
		  new Thread() {
	            public void run() {
            		try {
            			//如果是第�?次启动，点击确定后重�?
	                    if(!clickedOK){
                    	currentClickTime = System.currentTimeMillis();
							if((currentClickTime - lastClickTime) < 300000){
								lastClickTime = currentClickTime;
								return;
							}else{
								lastClickTime = currentClickTime;
							}
						  
							Thread.sleep(1000);
							//点击确定
							RootShellCmd rsc = new RootShellCmd();				       							        				
							rsc.exec(ROOTCMD); 	
							Log.d("Bililong", ROOTCMD);
							Thread.sleep(1000);
							killApp();
							Log.d("Bililong", "killapp");
							Thread.sleep(3000);
							Log.d("Bililong", "startapp");
							clickedOK = true;
	                    }
	        			startgame.startGameByName(appName);
	        			try{
	        				Thread.sleep(2000);
	        				RootShellCmd rsc = new RootShellCmd();				       							        				
	        				rsc.exec(ROOTCMD);
	        			}catch (InterruptedException e) {
		                    e.printStackTrace();
		                }	
	        			Thread.sleep(1000);
	        			if(packageName != "" && appRecord != null && startgame != null){
	        				//监测app运行状�??
	    					keepApp(packageName, appRecord, startgame);
	    				}
	                } catch (InterruptedException e) {
	                    e.printStackTrace();
	                }				           
	            }			                			                	                
		  }.start();
	  }
	  
	  @Override
		public void onDestroy() {
			super.onDestroy();
			unregisterReceiver(networkChangeReceiver);
			unregisterReceiver(appChangedReceiver);
//			localBroadcastManager.unregisterReceiver(localReceiver);
			
			AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
			Intent i = new Intent(this, AlarmReceiver.class); 
  		PendingIntent pi1 = PendingIntent.getBroadcast(this, 1, i, 0);
  		manager.cancel(pi1);
  		PendingIntent pi0 = PendingIntent.getBroadcast(this, 0, i, 0);
  		manager.cancel(pi0);
  		PendingIntent pi2 = PendingIntent.getBroadcast(this, 2, i, 0);
  		manager.cancel(pi2);
  		PendingIntent pi3 = PendingIntent.getBroadcast(this, 3, i, 0);
  		manager.cancel(pi3);
  		
			Log.v("Bililong","service destroyed");
			
		}
	  
	  class NetworkChangeReceiver extends BroadcastReceiver {

			@Override
			public void onReceive(Context context, Intent intent) {
				if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
					initNetwork();
				}
			}						
		}
	  
	  /** 
	* @ClassName: AppChangedReceiver 
	* @Description: 有app安装和卸载的广播 
	* @author lix 
	* @date 2015-12-16 下午5:21:05 
	*  
	*/
	class AppChangedReceiver extends BroadcastReceiver {
		  
			@Override
			public void onReceive(Context context, Intent intent) {				
				if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {     
		            String packageName = intent.getDataString();     
		            Log.d("Bililong","安装了:" +packageName);  
		            Toast.makeText(context, "安装了:" +packageName, Toast.LENGTH_LONG).show();	
		            //向map中写入app的状态
		            downloader.putMap(packageName);	
		        }     
				//接收卸载广播    
		        if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {     
		            String packageName = intent.getDataString();     
		            Log.d("Bililong","卸载了:" +packageName + "包名的程序");  
		        }
			}
		}
	  
	  /** 
	* @ClassName: LocalReceiver 
	* @Description: 手柄插卡广播 
	* @author lix 
	* @date 2015-12-16 下午5:19:02 
	*  
	*/
//	class LocalReceiver extends BroadcastReceiver {
//
//			@Override
//			public void onReceive(Context context, Intent intent) {
//				String action = intent.getAction();
//				if(action.equals("com.poobo.bailianlong.JOY_STICK_CHANGED_BROADCAST")){
//					Log.d("Bililong","Receive broadcast: Joy stick is changed");
//					
//					if(checkController != null){
//						checkController.stopThread();
//					}
//					AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
//					Intent i = new Intent(MainService.this, AlarmReceiver.class); 
//		    		PendingIntent pi1 = PendingIntent.getBroadcast(MainService.this, 1, i, 0);
//		    		manager.cancel(pi1);
//	  				clickOk();
//				}
//				
//				if(action.equals("com.poobo.bailianlong.JOY_STICK_LOSE_PERMISSION_LATER_BROADCAST")){
//					receiveBroadcastCount++;
//					
//					if(receiveBroadcastCount == 1){
//						if(checkController.checkPermission()){
//							  Log.e("Bililong", "has permission!!!! broadcast");
//							  losePermission = false;
//						  }else{
////							  if(losePermission == true){
////								  
////							  }else{
//								  losePermission = true;
//								  
//								  Log.e("Bililong", "no permission!!! broadcast"); 
//								  
//								  
//								  mclickOK = 9;
//								 
//								  Message msg = qmsgHandler.obtainMessage();  
//								  Bundle b = new Bundle();
//								  b.putString("String", "重新获取监控插卡权限LATER"); 
//								  msg.setData(b); 			              			 
//								  qmsgHandler.sendMessage(msg);  
//						}
////						  }
//					}
//				}
//				
//				
//				if(action.equals("com.poobo.bailianlong.JOY_STICK_LOSE_PERMISSION_BROADCAST")){
//					Log.e("Bililong", action +"  " + receiveBroadcastCount); 
//					receiveBroadcastCount++;
//					
//					if(receiveBroadcastCount == 1){
//						if(checkController.checkPermission()){
//							  Log.e("Bililong", "has permission!!!!");
//							  losePermission = false;
//						  }else{
////							  if(losePermission == true){
////								  
////							  }else{
//								  losePermission = true;
//								  
//								  Log.e("Bililong", "no permission!!!"); 
//								  
//								  mclickOK = 9;
//								  
//								  if(!gameIsRunning){
//									  Intent i = new Intent(MainService.this, AlarmReceiver.class); 
//									  PendingIntent pi = PendingIntent.getBroadcast(MainService.this, 1, i, 0);    		
//									  AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);	
//									  manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+5000,pi);   
//									  
//									  Message msg = qmsgHandler.obtainMessage();  
//									  Bundle b = new Bundle();
//									  b.putString("String", "重新获取监控插卡权限"); 
//									  msg.setData(b); 			              			 
//									  qmsgHandler.sendMessage(msg);  
//								  }else{
//									  Message msg = qmsgHandler.obtainMessage();  
//									  Bundle b = new Bundle();
//									  b.putString("String", "稍后重新获取监控插卡权限"); 
//									  msg.setData(b); 			              			 
//									  qmsgHandler.sendMessage(msg);  
//								  }
//						}
//							  
////						  }
//					}
//				}
//				
//			}
//		}
	  
	  /** 
	* @Title: upgradeRootPermission 
	* @Description: 获取root权限
	* @param @param pkgCodePath
	* @param @return    设定文件 
	* @return boolean    返回类型 
	* @throws 
	*/
	public static boolean upgradeRootPermission(String pkgCodePath) {
		    Process process = null;
		    DataOutputStream os = null;
		    try {
		        String cmd="chmod 777 " + pkgCodePath;
		        process = Runtime.getRuntime().exec("su"); 
		        os = new DataOutputStream(process.getOutputStream());
		        os.writeBytes(cmd + "\n");
		        os.writeBytes("exit\n");
		        os.flush();
		        process.waitFor();
		    } catch (Exception e) {
		        return false;
		    } finally {
		        try {
		            if (os != null) {
		                os.close();
		            }
		            process.destroy();
		        } catch (Exception e) {
		        }
		    }
		    return true;
		}
	  
	  private final Handler qmsgHandler = new Handler(){  
	        public void handleMessage(Message msg) {	     	        	
	        	 Bundle b = msg.getData(); 
	             String string = b.getString("String"); 
	            Toast.makeText(getApplicationContext(), string, 500).show();   
	            if(string == "update configure succeed"){
	            	Log.d("Bililong","circleNumber chongzhiwei 0");
	            	circleNumber = 0;
	            }
	        }  
	};  
	
  	 /**
	 * 刷新通知
	 * @param String tickerText
	 * @param String contentTitle
	 * @param String contentText
	 * @return 		  		
	 */
	  private void refreshNotification(String tickerText,String contentTitle,String contentText){
		    PendingIntent pendingIntent3 = PendingIntent.getActivity(this, 0,  
	                new Intent(this, MainActivity.class), 0); 				
			Notification notification = new Notification.Builder(this).setSmallIcon(R.drawable.ic_launcher)  
		                .setTicker("TickerText:" + tickerText)  
		                .setContentTitle(contentTitle)  
		                .setContentText(contentText)  
		                .setOngoing(true)
		                .setContentIntent(pendingIntent3).setNumber(1).build(); 
			startForeground(1, notification);
	  }
	  
		class RootShellCmd {  
			  
		    private OutputStream os;  
		  
		    public final void exec(String cmd) { 
		    	Log.e("Bililong","tap");
		        try {  
		            if (os == null) {  
		                os = Runtime.getRuntime().exec("su").getOutputStream();  
		            }  
		            os.write(cmd.getBytes());  
		            os.flush();  
		        } catch (Exception e) {  
		            e.printStackTrace();  
		        }  
		    } 
		} 
		//获取mac地址
		public static String getLocalMacAddressFromWifiInfo(Context context){
	         WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);  
	         WifiInfo info = wifi.getConnectionInfo();  
	         return info.getMacAddress(); 
	     }
		
		
		//跳转到wifi界面
		private void setConnected() {
			Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");  
			wifiSettingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(wifiSettingsIntent); 
		}
		
		private void initNetwork(){
			ConnectivityManager connectionManager = (ConnectivityManager)
					getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
					if (networkInfo != null && networkInfo.isAvailable()) {
						
						if(!isFirst){
							return;
						}
						isFirst = false;
						
						Intent intent2 = new Intent(MainService.this, MainActivity.class); 	
						    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);		      
						    startActivity(intent2);  
						new Thread() {
  	  			            public void run() {
//  	  			                try {		  
//  	  			                	Log.d("Bililong","再次执行任务");
//  	  			                Calendar cal2015 = Calendar.getInstance();
//  	  			                	cal2015.set(2015, 01, 01);
//  	  			                	while(System.currentTimeMillis() < cal2015.getTimeInMillis()){
//  	  			                	Message msg = qmsgHandler.obtainMessage();  
//  	  			                	Bundle b = new Bundle();
//  	  			                	b.putString("String", "系统时间错误"); 
//  	  			                	msg.setData(b); 			              			 
//  	  			                	qmsgHandler.sendMessage(msg);  
//  	  			                Log.d("Bililong","系统时间错误");
//  	  			                	sleep(3000);
//  	  	  			                }
//  	  			                } catch (InterruptedException e) {
//  	  			                    e.printStackTrace();
//  	  			                    
//  	  			                }
	  	  			            String macAdress = getLocalMacAddressFromWifiInfo(MainService.this);
	  							Log.e("Bililong", "the Mac address is: "+macAdress);
	  							
	  							Message msg = qmsgHandler.obtainMessage();  
	  			      			Bundle b = new Bundle();
	  			                b.putString("String", "Mac address:" + macAdress); 
	  			                msg.setData(b); 			              			 
	  			      			qmsgHandler.sendMessage(msg);  
	  							DEVICE_ID = macAdress;
	  							
	  							networkState = true;
	  							Log.d("Bililong","NetworkChangeReceiver init()");
//  	  							Toast.makeText(context, "init()", Toast.LENGTH_LONG).show();
	  				       	    init(); 
	  							startTask();
  	  			            }			        
  	  			        }.start();
  	  			        
					} else{
						Toast.makeText(MainService.this, "网络未连接", Toast.LENGTH_LONG).show();
						Log.d("Bililong","网络未连接");
					}
		}
		
}


